package com.retail.lottery.colalottery.utils;

import com.alibaba.excel.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class HeaderUtils {
    /**
     * 检查并添加请求头（如果不存在）
     * @param originalRequest 原始请求
     * @param headerName 要检查的请求头名称
     * @param headerValue 要添加的请求头值
     * @return 包装后的请求对象（如果添加了头）或原始请求对象（如果头已存在）
     */
    public static HttpServletRequest addHeaderIfMissing(HttpServletRequest originalRequest,
                                                        String headerName,
                                                        String headerValue) {
        if (StringUtils.isBlank(originalRequest.getHeader(headerName))) {
            return new HttpServletRequestWrapper(originalRequest) {
                private final Map<String, String> addedHeaders = new HashMap<>();
                {
                    addedHeaders.put(headerName, headerValue);
                }
                @Override
                public String getHeader(String name) {
                    if (addedHeaders.containsKey(name)) {
                        return addedHeaders.get(name);
                    }
                    return super.getHeader(name);
                }
                @Override
                public Enumeration<String> getHeaders(String name) {
                    if (addedHeaders.containsKey(name)) {
                        return Collections.enumeration(Collections.singletonList(addedHeaders.get(name)));
                    }
                    return super.getHeaders(name);
                }
                @Override
                public Enumeration<String> getHeaderNames() {
                    Enumeration<String> originalHeaderNames = super.getHeaderNames();
                    return Collections.enumeration(
                            Collections.list(originalHeaderNames).stream()
                                    .filter(name -> !addedHeaders.containsKey(name))
                                    .collect(Collectors.toList())
                    );
                }
            };
        }
        return originalRequest;
    }


}
